import sys
import threading
import traceback
from datetime import datetime

from fastapi import APIRouter
from starlette.responses import PlainTextResponse, RedirectResponse

from app.api.item.controllers.item_controller import router as item_router
from app.api.scheduler.controllers.scheduler_controller import router as scheduler_router
from app.api.user.controllers.user_controller import router as user_router
from app.core.config import settings

router = APIRouter()


@router.get("/", include_in_schema=False)
async def index():
    return PlainTextResponse("Welcome to the API!")


@router.get("/dump_thread_stacks", include_in_schema=False)
async def dump_thread_stacks(key: str = None):
    if key != datetime.now().strftime("%Y%m%d"):
        return RedirectResponse(url=f"{settings.CONTEXT_PATH}/")
    """导出所有线程的堆栈信息"""
    thread_stacks = []
    for thread_id, stack_frame in sys._current_frames().items():
        # 获取线程名
        thread_name = threading._active.get(thread_id, threading.Thread()).name
        thread_stacks.append(f"Thread ID: {thread_id}, Thread Name: {thread_name}")
        thread_stacks.append("".join(traceback.format_stack(stack_frame)))
    return PlainTextResponse("\n".join(thread_stacks))


router.include_router(item_router)
router.include_router(user_router)
router.include_router(scheduler_router)

# if settings.ENVIRONMENT == "dev":
#     router.include_router(test_router)
